#!/usr/bin/env python3
"""
启动脚本
检查依赖并启动Meiya SQL生成工具
"""

import sys
import subprocess
import importlib.util

def check_and_install_requirements():
    """检查并安装必要的依赖包"""
    required_packages = {
        'customtkinter': 'customtkinter>=5.2.0',
        'pandas': 'pandas>=2.0.0',
        'openpyxl': 'openpyxl>=3.1.0'
    }
    
    missing_packages = []
    
    for package_name, package_spec in required_packages.items():
        if importlib.util.find_spec(package_name) is None:
            missing_packages.append(package_spec)
    
    if missing_packages:
        print("检测到缺少以下依赖包:")
        for pkg in missing_packages:
            print(f"  - {pkg}")
        
        print("\n正在安装缺少的依赖包...")
        try:
            subprocess.check_call([
                sys.executable, '-m', 'pip', 'install'
            ] + missing_packages)
            print("✅ 依赖包安装完成！")
        except subprocess.CalledProcessError as e:
            print(f"❌ 依赖包安装失败: {e}")
            print("\n请手动运行: pip install -r requirements.txt")
            return False
    else:
        print("✅ 所有依赖包已就绪！")
    
    return True

def main():
    """主函数"""
    print("=" * 50)
    print("  Meiya SQL生成工具启动器")
    print("=" * 50)
    
    # 检查Python版本
    if sys.version_info < (3, 8):
        print("❌ 错误: 需要Python 3.8或更高版本")
        print(f"当前版本: {sys.version}")
        sys.exit(1)
    
    print(f"✅ Python版本检查通过: {sys.version.split()[0]}")
    
    # 检查并安装依赖
    if not check_and_install_requirements():
        sys.exit(1)
    
    # 启动主程序
    try:
        print("\n🚀 启动Meiya SQL生成工具...")
        from gui_main import main as gui_main
        gui_main()
    except Exception as e:
        print(f"❌ 启动失败: {e}")
        print("\n请检查是否有语法错误或缺少依赖包")
        sys.exit(1)

if __name__ == "__main__":
    main()
